﻿define(['util', 'ajax'], function (util, ajax) {
    "use strict";

    var exports = {},
        Attachment, ViewModel;

    Attachment = function (data) {
        var self = this;
        self.id = ko.observable(data.id);
        self.name = ko.observable(data.name);
        self.tags = ko.observable(data.tags);
        self.entityTypeName = ko.observable(data.entityTypeName);
        self.referenceId = ko.observable(data.referenceId);
        self.referenceName = ko.observable(data.referenceName);
        self.createdBy = ko.observable(data.createdBy);
        self.createdByName = ko.observable(data.createdByName);
        self.createdOn = ko.observable(moment(data.createdOn).format("YYYY-MM-DD HH:mm:ss"));

        self.parentUrl = ko.observable('/' + self.entityTypeName() + '/show?id=' + self.referenceId());
    };

    ViewModel = function (data) {
        var self = this;
        self.entityTypes = ko.observableArray(data.entityTypes);
        self.attachments = ko.observableArray([]);
        var url = document.URL;
        var urlValue = url.split('=');
        var searchValue = urlValue[urlValue.length - 1];
        self.value = ko.observable(searchValue);
        console.log(self.value());
        self.search = function () {
            var form = {
                id: self.value()
            };

            ajax.get('Search', form).done(function (response) {
                self.attachments([]);
                $.each(response.attachmentLines, function (row, a) {
                    self.attachments.push(new Attachment(a, self));
                });
            });
        };

        $.each(data.attachmentLines, function (row, a) {
            self.attachments.push(new Attachment(a, self));
        });
    };

    exports.exec = function (sectionId, model) {
        var viewModel = new ViewModel(model);
        ko.applyBindings(viewModel, document.getElementById(sectionId));
    };

    return exports;
});